<template>
  <div>
    <Checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
    >
      全选
    </Checkbox>
    <div style="margin: 15px 0;" />
    <CheckboxGroup
      :options="options"
      :value="checkedList"
      @options-change="handleChange"
    />
  </div>
</template>

<script setup name="basic-select-all">
import { ref, unref } from 'vue'
import CheckboxGroup from './CheckboxGroup.vue'

const props = defineProps({
  value: {
    type: [String, Array],
    default: ''
  },
  options: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['options-change'])

const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedList = ref(
  Array.isArray(props.value) ? props.value : [props.value]
)
const options = ref(props.options)

function handleCheckAllChange(e) {
  if (e) {
    checkedList.value = options.value.map(item => item.label)
  } else {
    checkedList.value = []
  }

  isIndeterminate.value = false
  emit('options-change', unref(checkedList))
}

function handleChange(value) {
  checkedList.value = value
  const checkedCount = value.length
  checkAll.value = checkedCount === unref(options).length
  isIndeterminate.value =
        checkedCount > 0 && checkedCount < unref(options).length
  emit('options-change', unref(checkedList))
}
</script>
